#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
链路追踪相关路由
"""

import logging
import json
from flask import Blueprint, request, jsonify
from base.services.trace_service import TraceService

logger = logging.getLogger(__name__)

# 创建蓝图
traces_bp = Blueprint('traces', __name__)

@traces_bp.route('/', methods=['POST'])
def create_trace():
    """创建链路追踪记录"""
    try:
        data = request.json
        if not data:
            return jsonify({"error": "请求体不能为空"}), 400
        
        # 获取请求定义和链路数据
        request_definition = data.get('request_definition', {})
        trace_data = data.get('trace_data', [])
        
        if not trace_data:
            return jsonify({"error": "链路数据不能为空"}), 400
        
        # 创建链路记录
        trace_id = TraceService.create_trace(request_definition, trace_data)
        
        return jsonify({
            "message": "链路追踪记录创建成功",
            "trace_id": trace_id
        }), 201
    
    except Exception as e:
        logger.error(f"创建链路追踪记录失败: {e}")
        return jsonify({"error": f"创建链路追踪记录失败: {str(e)}"}), 500

@traces_bp.route('/', methods=['GET'])
def get_traces():
    """获取链路列表"""
    try:
        # 获取分页参数
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 10))
        
        # 获取链路列表
        result = TraceService.get_traces(page, page_size)
        
        return jsonify(result), 200
    
    except Exception as e:
        logger.error(f"获取链路列表失败: {e}")
        return jsonify({"error": f"获取链路列表失败: {str(e)}"}), 500

@traces_bp.route('/<trace_id>', methods=['GET'])
def get_trace(trace_id):
    """获取链路详情"""
    try:
        # 获取链路详情
        trace = TraceService.get_trace_by_id(trace_id)
        
        if not trace:
            return jsonify({"error": "链路不存在"}), 404
        
        return jsonify(trace), 200
    
    except Exception as e:
        logger.error(f"获取链路详情失败: {e}")
        return jsonify({"error": f"获取链路详情失败: {str(e)}"}), 500

@traces_bp.route('/<trace_id>/services', methods=['GET'])
def get_trace_services(trace_id):
    """获取链路服务列表"""
    try:
        # 获取链路服务列表
        services = TraceService.get_trace_services(trace_id)
        
        return jsonify(services), 200
    
    except Exception as e:
        logger.error(f"获取链路服务列表失败: {e}")
        return jsonify({"error": f"获取链路服务列表失败: {str(e)}"}), 500

@traces_bp.route('/<trace_id>/topology', methods=['GET'])
def get_trace_topology(trace_id):
    """获取链路拓扑关系"""
    try:
        # 获取链路拓扑关系
        topology = TraceService.get_trace_topology(trace_id)
        
        return jsonify(topology), 200
    
    except Exception as e:
        logger.error(f"获取链路拓扑关系失败: {e}")
        return jsonify({"error": f"获取链路拓扑关系失败: {str(e)}"}), 500

@traces_bp.route('/services/<service_id>/requests', methods=['GET'])
def get_service_requests(service_id):
    """获取服务请求信息"""
    try:
        # 获取服务请求信息
        requests = TraceService.get_service_requests(service_id)
        
        return jsonify(requests), 200
    
    except Exception as e:
        logger.error(f"获取服务请求信息失败: {e}")
        return jsonify({"error": f"获取服务请求信息失败: {str(e)}"}), 500

@traces_bp.route('/<trace_id>', methods=['DELETE'])
def delete_trace(trace_id):
    """删除链路记录"""
    try:
        # 删除链路记录
        success = TraceService.delete_trace(trace_id)
        
        if not success:
            return jsonify({"error": "链路不存在"}), 404
        
        return jsonify({"message": "链路记录删除成功"}), 200
    
    except Exception as e:
        logger.error(f"删除链路记录失败: {e}")
        return jsonify({"error": f"删除链路记录失败: {str(e)}"}), 500
